package com.shbaiche.bifenba.ui.data;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.sevenheaven.segmentcontrol.SegmentControl;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.data.DataIntegralListAdapter;
import com.shbaiche.bifenba.adapter.data.DataPlayerListAdapter;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.GankResults;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.data.ShooterMessage;
import com.shbaiche.bifenba.model.data.ShooterVo;
import com.shbaiche.bifenba.model.data.ShooterVoBox;
import com.shbaiche.bifenba.model.data.StandingMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroid.base.SimpleRecAdapter;
import cn.droidlover.xdroid.base.XLazyFragment;
import cn.droidlover.xdroidbase.kit.Kits;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerContentLayout;
import cn.droidlover.xrecyclerview.XRecyclerView;
import okhttp3.Call;

/**
 * 数据球队榜
 */

@SuppressLint("ValidFragment")
public class DataPlayerFragment extends XLazyFragment {

    @BindView(R.id.segment_control)
    SegmentControl boxControl;


    @BindView(R.id.contentLayout)
    XRecyclerContentLayout contentLayout;

    DataPlayerListAdapter adapter;

    CompeteVo mCompeteVo;

    List<ShooterVoBox> boxList;

    String year = "";

    protected static final int PAGE_SIZE = 10;
    protected static final int MAX_PAGE = 10;

    @SuppressLint("ValidFragment")
    public DataPlayerFragment(){
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event.EventYearChange event) {
        if (event != null && !Kits.Empty.check(event.year)) {
            if(mCompeteVo.equals(event.vo)){
                year = event.year;
                contentLayout.showLoading();
                loadData();
            }
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        Log.e("t","initData player");
        if(savedInstanceState!=null && savedInstanceState.containsKey("data")){
            mCompeteVo = (CompeteVo)savedInstanceState.getSerializable("data");
        }else{
            mCompeteVo = (CompeteVo)getArguments().getSerializable("data");
        }

        if(savedInstanceState!=null && savedInstanceState.containsKey("year")){
            year = savedInstanceState.getString("year");
        }else{
            year = getArguments().getString("year");
        }


        if(TextUtils.isEmpty(year)){
            if(mCompeteVo!=null && mCompeteVo.getShooterYear()!=null && mCompeteVo.getShooterYear().size()>0){
                year = mCompeteVo.getShooterYear().get(0);
            }else{
                int y = new Date(System.currentTimeMillis()).getYear();
                y += 1900;
                year = ""+y;
            }
        }


        initAdapter();
        contentLayout.showLoading();
        loadData();

        boxControl.setOnSegmentControlClickListener(new SegmentControl.OnSegmentControlClickListener() {
            @Override
            public void onSegmentControlClick(int index) {
                setAdapterData(index);
            }
        });
    }

    private void setAdapterData(int index){
        if(boxList!=null && adapter!=null && boxList.size()>index){
            getAdapter().setData(boxList.get(index).getVoList());

            if (getAdapter().getItemCount() < 1) {
                contentLayout.showEmpty();
                return;
            }
        }
    }

    private void initAdapter() {
        setLayoutManager(contentLayout.getRecyclerView());
        contentLayout.getRecyclerView()
                .setAdapter(getAdapter());
        contentLayout.getRecyclerView()
                .setOnRefreshAndLoadMoreListener(new XRecyclerView.OnRefreshAndLoadMoreListener() {
                    @Override
                    public void onRefresh() {
                        loadData();
                    }

                    @Override
                    public void onLoadMore(int page) {

                    }
                });

        contentLayout.loadingView(View.inflate(getContext(), R.layout.view_loading, null));
        contentLayout.getRecyclerView().useDefLoadMoreView();

        contentLayout.getEmptyView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentLayout.showLoading();
                loadData();
            }
        });
    }

    public void loadData() {
        ShooterMessage message = new ShooterMessage();
            message.setCompetId(mCompeteVo.getId());
            message.setGameType(mCompeteVo.getGameType());
            message.setYear(year);

            NetApi.dataPlayerRank(message, new JsonCallback<TransMessage>() {
                @Override
                public void onFail(Call call, Exception e, int id) {
                    contentLayout.showContent();
                    contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                    ToastUtil.show("onFail" + e.getMessage());
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    contentLayout.showContent();
                    contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                    ToastUtil.show("onFail" + e.getMessage());

                }

                @Override
                public void onResponse(TransMessage response, int id) {
                    contentLayout.showContent();
                    contentLayout.getSwipeRefreshLayout().setRefreshing(false);
                    ShooterMessage result =new Gson().fromJson(response.getMessage(),ShooterMessage.class);
                    if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                        if(result!=null && result.getBox()!=null){
                            Log.e("t","onResponse");
                            setData(result.getBox());

                            if (getAdapter().getItemCount() < 1) {
                                contentLayout.showEmpty();
                                return;
                            }

                        }
                    }else{
                        Log.e("t","onResponse getCode "+response.getCode());
                        ToastUtil.show(result.getMessage());
                    }
                }
            });

    }

    private void setData(List<ShooterVoBox> box){
        if(box!=null){
            boxList = box;
            String[] names = new String[box.size()];
            ShooterVoBox list;
            for (int i= 0;i<box.size();i++){
                list = box.get(i);
                names[i] = list.getName();
            }
            boxControl.setText(names);
            boxControl.setSelectedIndex(0);
            setAdapterData(0);
        }

    }

    public SimpleRecAdapter getAdapter() {
        if (adapter == null) {
            adapter = new DataPlayerListAdapter(context);
            adapter.setRecItemClick(new RecyclerItemCallback<ShooterVo, DataPlayerListAdapter.ViewHolder>() {
                @Override
                public void onItemClick(int position, ShooterVo model, int tag, DataPlayerListAdapter.ViewHolder holder) {
                    super.onItemClick(position, model, tag, holder);
                }
            });
        }
        return adapter;
    }


    public void setLayoutManager(XRecyclerView recyclerView) {
        recyclerView.verticalLayoutManager(context);
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_data_player;
    }

}
